<template>
  <!-- 重置密码弹框 -->
  <el-dialog v-model="visible" title="修改密码" :width="dialogWidth" :draggable="true" :before-close="handleClose"
    :close-on-click-modal="false" class="reset-password-dialog">
    <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px"
      class="password-form">
      <!-- 当前密码 -->
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input v-model="passwordForm.currentPassword" type="currentPasswordVisible ? 'text' : 'password'" clearable
          placeholder="请输入当前密码" prefix-icon="Lock" show-password :show-password="showPassword" class="password-input">
        </el-input>
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" :type="newPasswordVisible ? 'text' : 'password'" clearable
          prefix-icon="Lock" show-password :show-password="showPassword" placeholder="请输入新密码"
          autocomplete="new-password" class="password-input">
        </el-input>
        <!-- 密码强度提示 -->
        <div class="password-hint">
          <p>密码要求：</p>
          <ul>
            <li :class="{ 'hint-passed': checkPasswordLength }">至少8个字符</li>
            <li :class="{ 'hint-passed': checkPasswordHasLetter }">包含字母</li>
            <li :class="{ 'hint-passed': checkPasswordHasNumber }">包含数字</li>
          </ul>
        </div>
      </el-form-item>

      <!-- 确认新密码 -->
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" :type="confirmPasswordVisible ? 'text' : 'password'"
          placeholder="请再次输入新密码" autocomplete="new-password" clearable prefix-icon="Lock" show-password
          :show-password="showPassword" class="password-input">
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认重置</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/api/request';
import { encryptPassword } from '@/components/utils/rsaEncrypt';
import auth from '@/components/utils/auth';

// 弹框可见性控制
const visible = ref(false);

// 密码表单数据
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码可见性切换
const currentPasswordVisible = ref(false);
const newPasswordVisible = ref(false);
const confirmPasswordVisible = ref(false);

// 密码验证状态跟踪
const checkPasswordLength = ref(false);
const checkPasswordHasLetter = ref(false);
const checkPasswordHasNumber = ref(false);

// 监听新密码变化，实时更新验证状态
watch(
  () => passwordForm.newPassword,
  (newVal) => {
    checkPasswordLength.value = newVal.length >= 8;
    checkPasswordHasLetter.value = /[a-zA-Z]/.test(newVal);
    checkPasswordHasNumber.value = /\d/.test(newVal);
  }
);

// 表单验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 8) {
          callback(new Error('密码长度不能少于8个字符'));
        } else if (!/[a-zA-Z]/.test(value)) {
          callback(new Error('密码必须包含字母'));
        } else if (!/\d/.test(value)) {
          callback(new Error('密码必须包含数字'));
        } else if (value === passwordForm.currentPassword) {
          callback(new Error('新密码不能与当前密码相同'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 表单引用
const passwordFormRef = ref(null);

// 弹框宽度（响应式）
const dialogWidth = ref('450px');

// 打开弹框方法
const open = () => {
  visible.value = true;
  resetForm();
};

// 关闭弹框处理
const handleClose = () => {
  visible.value = false;
  resetForm();
};

// 取消操作
const handleCancel = () => {
  visible.value = false;
  resetForm();
};

// 提交表单处理
const handleSubmit = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      /**
       * 密码加密传输
       */

      const userInfo = auth.getUserInfo()

      // 1. 用 RSA 公钥加密密码
      const oldPassword = encryptPassword(passwordForm.currentPassword);
      if (!oldPassword) {
        alert('密码加密失败');
        return;
      }
      const newPassword = encryptPassword(passwordForm.newPassword);
      const form = {
        userId: userInfo.id,
        oldPassword: oldPassword,
        newPassword: newPassword
      }
      request.post("user/restPassword", form, {
        headers: {
          'Content-Type': 'multipart/form-data' // 问题所在！
        }
      }).then(res => {
        if (res.success) {
          ElMessage.success(res.message);
          visible.value = false;
          resetForm();
        } else {
          ElMessage.error(res.message);
        }
      })
    } else {
      ElMessage.error('请检查输入的信息');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  passwordForm.currentPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';

  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }

  checkPasswordLength.value = false;
  checkPasswordHasLetter.value = false;
  checkPasswordHasNumber.value = false;
};

// 暴露open方法供父组件调用
defineExpose({
  open
});
</script>

<style scoped>
.reset-password-dialog {
  --el-dialog-padding-primary: 20px;
}

.password-form {
  margin-top: 10px;
}

.password-input {
  width: 100%;
}

.visibility-icon {
  cursor: pointer;
  color: var(--el-text-color-secondary);
  transition: color 0.2s;

  &:hover {
    color: var(--el-color-primary);
  }
}

.password-hint {
  margin-top: 5px;
  font-size: 12px;
  color: var(--el-text-color-secondary);

  p {
    margin: 0 0 3px 0;
    font-weight: 500;
  }

  ul {
    margin: 0;
    padding-left: 18px;

    li {
      margin: 2px 0;
      transition: color 0.2s;
    }
  }
}

.hint-passed {
  color: var(--el-color-success);
}

/* 动画效果优化 */
:v-deep(.el-input__wrapper) {
  transition: all 0.3s ease;
}

:v-deep(.el-button) {
  transition: all 0.2s ease;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .reset-password-dialog {
    width: 90% !important;
    margin: 0 auto;
  }
}
</style>